<!--
编辑器

v-model:value    =====>   双向数据绑定
height           =====>   编辑器高度
theme            =====>   编辑器主题，默认snow
mode             =====>   模式，simple / full
-->
<template>
  <div ref="editorRef" class="s-editor" :style="{'height': height}"></div>
</template>

<script setup>
import Quill from 'quill'
// 编辑器的css
import 'quill/dist/quill.snow.css'
import { markRaw, nextTick, onMounted, ref, watch } from 'vue'
const emit = defineEmits(['update:value'])
const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  height: {
    type: [String,Number],
    default: '300px',
  },
  placeholder: {
    type: String,
    default: '请输入内容'
  },
  theme: {
    type: String,
    default: 'snow'
  },
  mode: {
    type: String,
    default: 'simple'
  }
})
let editor = null // 编辑器
const editorRef = ref(null)

const toolbarFullOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],

  ['clean', 'image']
]
const toolbarSimpleOptions = [
  [{ 'header': 1 }, { 'header': 2 }],
  ['bold', 'italic', 'underline'],
  ['blockquote', 'code-block'],
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'align': [] }],
  ['clean', 'image']
]
const options = ref({
  // debug: 'error',  // 启用调试 'error', 'warn', 'log', 'info'
  modules: {
    toolbar: props.mode === 'simple' ? toolbarSimpleOptions : toolbarFullOptions
  },
  placeholder: props.placeholder,
  readOnly: false,
  theme: props.theme
})
onMounted(() => {

  nextTick(() => {
    editor = markRaw(new Quill(editorRef.value, options.value))
    editor.on('text-change', () => {
      const content = editor.getText();
      emit('update:value', content)
    })
    if(props.value) {
      editor.setText(props.value)
    }
  })

})

const setContent = (content) => {
  if(editor != null) {
    editor.setText(content)
  }else{
    console.log('编辑器未准备好')
  }
}
// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({ setContent })
</script>

<style scoped lang="scss">
.s-editor {font-size: 14px;border: 1px solid #ddd;line-height: 150%;}
//.s-editor:deep(.CodeMirror)  {height: 100%;}
</style>
